package cn.lyd.org.service.impl;

import cn.lyd.basic.service.impl.BaseServiceImpl;
import cn.lyd.org.domain.Department;
import cn.lyd.org.mapper.DepartmentMapper;
import cn.lyd.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl  extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        //1.查出所有的部门
        List<Department> departments = departmentMapper.findAll();
        //2.创建map集合---将key设为每个部门的id，val设置为id对应的部门
        Map<Long, Department> map = new HashMap<>();
        //3.遍历所有部门，装进map里
        for (Department department : departments){
            map.put(department.getId(),department);
        }
        //4.创建部门树集合
        List<Department> deptTree = new ArrayList<>();
        //5.遍历所有部门，判断该部门是顶级部门还是子部门，判断有没有父部门
        for (Department department: departments) {
            //5.1判断是不是顶级部门
            if (department.getParent_id()==null){
                //5.1.1是顶级部门，装进部门树
                deptTree.add(department);
            }else {
                //5.1.2不是顶级部门，看他的父部门是什么(通过父部门id，map集合获取)
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);

                    //5.1.2.1如果父部门存在()，把这个部门加到父部门的子部门里
                    if (parentDepartment!=null){
                        parentDepartment.getChildren().add(department);
                    }
            }
        }
        //返回部门树集合
        return deptTree;
    }
}
